import {
  CategoriesItem,
  Exams,
  Papers,
  Question,
  getCategories,
  getNoAnswerPaper,
  getPapers,
  getPersonalExams,
} from "@/api/question";
import { Button, Card, List, Pagination } from "antd";
import CheckableTag from "antd/es/tag/CheckableTag";
import moment from "moment";
import { useEffect, useState } from "react";
import { useNavigate } from "react-router-dom";

const rulesMap = {
  select: "单选/多选",
  simple: "简答",
  code: "编程",
};

const WrittenTest = () => {
  const [isPersonal, setIsPersonal] = useState(false);

  const [papers, setPapers] = useState<Papers[]>([]);
  const [exams, setExams] = useState<Exams[]>([]);
  const [categories, setCategories] = useState<string[]>([]);
  const [selectCategory, setSelectCategory] = useState("全部");
  const navigate = useNavigate();
  const [page, setPage] = useState(1);

  useEffect(() => {
    if (!isPersonal) {
      getPapers({
        isOpen: "是",
        categories: selectCategory === "全部" ? undefined : selectCategory,
      }).then((res) => {
        setPapers(res);
      });
    } else {
      getPersonalExams().then((res) => {
        setExams(res);
      });
    }
  }, [isPersonal, selectCategory]);

  useEffect(() => {
    getCategories().then((res) => {
      setCategories(["全部"].concat(res.map((it) => it.categoryName)));
    });
  }, []);

  const toPractice = (content: string) => {
    const questions = JSON.parse(content);
    navigate("/practice", {
      state: {
        questions,
        isOpen: true,
      },
    });
  };

  const toExam = (examID: number, paperID: string, endTime: number) => {
    getNoAnswerPaper({
      paperID,
    }).then((res) => {
      navigate("/practice", {
        state: {
          questions: res,
          isExam: true,
        },
      });
    });
  };

  return (
    <>
      <div>
        <div style={{ position: "absolute", right: 0 }}>
          <Button type="link" onClick={() => setIsPersonal(!isPersonal)}>
            {isPersonal ? "切换企业真题练习" : "查看个人考试"}
          </Button>
        </div>
        {!isPersonal ? (
          <div>
            <div style={{ paddingTop: "15px" }}>
              {categories.map((category) => (
                <CheckableTag
                  key={category}
                  checked={category === selectCategory}
                  onChange={() => setSelectCategory(category)}
                >
                  {category}
                </CheckableTag>
              ))}
            </div>
            <div
              style={{
                width: "100%",
                display: "grid",
                gridTemplateColumns: "repeat(3, 1fr)",
                gap: "10px",
              }}
            >
              {papers
                .slice((page - 1) * 9, page * 9)
                .map(({ _id, paperContent, rules, paperName }) => {
                  const paper = JSON.parse(paperContent);
                  const rulesObj = JSON.parse(rules);
                  const total = paper.length ?? 0;
                  const simpleCount =
                    paper.filter((it: Question) => it.type === "简答题")
                      .length ?? 0;
                  const codeCount =
                    paper.filter((it: Question) => it.type === "编程题")
                      .length ?? 0;
                  const selectCount = total - simpleCount - codeCount;
                  const selectScore = rulesObj[rulesMap.select] * selectCount;
                  const simpleScore = rulesObj[rulesMap.simple] * simpleCount;
                  const codeScore = rulesObj[rulesMap.code] * codeCount;
                  const totalScore = codeScore + selectScore + simpleScore;
                  return (
                    <Card
                      title={paperName}
                      extra={
                        <Button
                          type="link"
                          onClick={() => toPractice(paperContent)}
                        >
                          去答题
                        </Button>
                      }
                      style={{ width: 300, marginTop: "20px" }}
                      key={_id}
                    >
                      <p>
                        总计：{total}道题（{totalScore}分）
                      </p>
                      <p>
                        {rulesMap.select}（{selectCount}道）：{selectScore}分
                      </p>
                      <p>
                        {rulesMap.simple}（{simpleCount}道）：{simpleScore}分
                      </p>
                      <p>
                        {rulesMap.code}（{codeCount}道）：{codeScore}分
                      </p>
                    </Card>
                  );
                })}
            </div>
          </div>
        ) : (
          <div>
            <h2 style={{ textAlign: "center" }}>我的参与的笔试</h2>
            <List
              itemLayout="horizontal"
              bordered
              dataSource={exams}
              renderItem={({ paperID, _id, examName, startTime, endTime }) => (
                <List.Item
                  actions={[
                    moment().valueOf() < startTime ? (
                      <a href="#">暂未开始</a>
                    ) : moment().valueOf() > endTime ? (
                      <a href="#">已经结束</a>
                    ) : (
                      <Button
                        type="link"
                        onClick={() => toExam(_id, paperID, endTime)}
                      >
                        去测试
                      </Button>
                    ),
                  ]}
                >
                  <h4>{examName}</h4>
                </List.Item>
              )}
            />
          </div>
        )}
      </div>
      <Pagination
        style={{ position: "fixed", bottom: "5%", right: 100 }}
        current={page}
        pageSize={9}
        hideOnSinglePage
        total={papers.length}
        onChange={(v) => setPage(v)}
      />
    </>
  );
};

export default WrittenTest;
